#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void func() {
    FILE * fp;
    int i = 20, j = 30, k, l;
    fp = fopen("./files/test.dat", "w");
    fprintf(fp, "%d\n", i); // 将内存变量中的数据"打印"到文件中
    fprintf(fp, "%d\n", j);
    fclose(fp);

    fp = fopen("./files/test.dat", "r");
    fscanf(fp, "%d%d", &k, &l); // 将文件中的数据"输入"到内存变量中
    printf("k = %d, l = %d\n", k, l);
    fclose(fp);

    int m = 0, n = 0;
    fp = fopen("./files/test2.dat", "w");
    for (i = 1; i < 4; ++i){
        fprintf(fp, "%d", i);
    }
    fclose(fp);

    fp = fopen("./files/test2.dat", "r");
    fscanf(fp, "%d%d", &m, &n); // 将文件中的数据"输入"到内存变量中
    printf("m = %d, n = %d\n", m, n);
    fseek(fp, 0L, SEEK_END); // 将文件指针移动到文件末尾
    int filesize = ftell(fp); // 获取位置指针当前位置，即该文件的大小（所占字节数）
    printf("文件大小：%d\n", filesize);
    int number = fseek(fp, 1L, SEEK_SET);
    printf("%c\n", fgetc(fp));
    fclose(fp);

    char str[10] = "abcdefghi";
    fp = fopen("./files/test3.dat", "wb");
    fputs(str, fp);
    fputs("\n1234", fp);
    fclose(fp);

    fp = fopen("./files/test3.dat", "rb");
    fgets(str, 8, fp);
    printf("str = ");
    printf("%s", str);
    fgets(str, 8, fp);
    printf("%s\n", str);
    fclose(fp);

    int arr[3] = {1, 2, 3};
    fp = fopen("./files/test4.dat", "wb");
    for (int i = 0; i < 3; ++i){
        fwrite(&arr[i], sizeof(int), 1, fp);
    }
    fclose(fp);

    fp = fopen("./files/test4.dat", "rb");
    int num;
    fseek(fp, -(long)(2 * sizeof(int)), SEEK_END);
    fread(&num, sizeof(int), 1, fp);
    printf("num = %d\n", num);

    char *str1 = "first", *str2 = "second", tmp[1024];
    fp = fopen("./files/test5.dat", "w+");
    fwrite(str2, 6, 1, fp);
    fseek(fp, 0L, SEEK_SET); // 等价于 rewind(fp);
    fwrite(str1, 5, 1, fp);
    fseek(fp, 0L, SEEK_SET);
    fscanf(fp, "%s", &tmp);
    printf("tmp = %s\n", tmp);
    fclose(fp);

    fp = fopen("./files/test6.dat", "a+"); // 以追加写入方式打开文件
    fwrite(str2, 6, 1, fp);
    fseek(fp, 0L, SEEK_SET);
    fwrite(str1, 5, 1, fp); // 无论文件内部指针在何处，只能在文件末尾追加写入
    fseek(fp, 0L, SEEK_SET);
    fscanf(fp, "%s", &tmp);
    printf("tmp = %s\n", tmp);
    fclose(fp);

    fp = fopen("./files/test7.dat", "w");
    for (i = 1; i <= 10; ++i) {
        fprintf(fp, "%3d", i);
    }
    for (i = 0; i < 10; ++i) {
        fseek(fp, i*3L, SEEK_SET);
        fscanf(fp, "%d", &n);
        printf("%3d", n);
    }
    printf("\n");
    fclose(fp);

    fp = fopen("./files/test7.dat", "r");
    for (i = 0; i < 10; ++i) {
        fseek(fp, i*3L, SEEK_SET);
        fscanf(fp, "%d", &n);
        printf("%3d", n);
    }
    // %d格式字符会自动跳过空白字符，直至寻找到第一个有效数字，但不能跳过a、!等字符
    printf("\n");
    fclose(fp);

}

int main() {
    func();
    return 0;
}